#给定多边形 进行绘制
import numpy as np
import matplotlib.pyplot as plt
import _query

def getColor(population):
    '''
        para population:float 人口数目
        return 绘图颜色
    '''
    if population < 0:
        return 'white'
    elif population < 0.1:
        return 'yellow'
    elif population < 0.2:
        return 'brown'
    elif population < 0.5:
        return 'orange'
    else:
        return 'red'

def plotPolygonal(polygonal_data,retList):
    '''
        para polygonal_data : geojson
                data = {
                    "type":"Polygon",
                    "coordinates":[[30.0,10.0],[40.0,40.0],[20.0,40.0],[10.0,20.0],[30.0,10.0]]
                }
        para retList : []
    '''
    # data = {
    #     "type":"Polygon",
    #     "coordinates":[[30.0,10.0],[40.0,40.0],[20.0,40.0],[10.0,20.0],[30.0,10.0]]
    # }
    # polygonal_data = data
    plen = len(polygonal_data["coordinates"]) #凸多边形边数
    print(plen)
    #转换坐标
    px = np.zeros(plen)
    py = np.zeros(plen)
    for i in range(plen):
        px[i] = polygonal_data["coordinates"][i][0]
        py[i] = polygonal_data["coordinates"][i][1]
        print(f'[{px[i]},{py[i]}]')
    #绘制多边形
    plt.plot(px, py)
    plt.fill(px, py, 'grey')
    
    #绘制矩形
    Rec_point = _query.findRectangle(polygonal_data["coordinates"])
    print(f'{Rec_point[0]} {Rec_point[1]}')
    #右上角
    Rec_right = Rec_point[0][0]
    Rec_up = Rec_point[0][1]
    #左下角
    Rec_left = Rec_point[1][0]
    Rec_down = Rec_point[1][1]
    #左下角 右下角 右上角 左上角 左下角
    rpx = np.zeros(5)
    rpy = np.zeros(5)
    rpx[0] = rpx[3] = rpx[4] = Rec_left
    rpx[1] = rpx[2] = Rec_right
    rpy[0] = rpy[1] = rpy[4] = Rec_down
    rpy[2] = rpy[3] = Rec_up
    plt.plot(rpx,rpy)

    #设置x,y轴范围
    plt.xlim((-180,180))
    plt.ylim((-90,90))
    #设置坐标轴名称
    plt.xlabel('longitude',loc='right')
    plt.ylabel('latitude',loc='top')

    #将坐标轴移动到0处
    ax=plt.gca()  #gca:gcet urrent axis得到当前轴
    #设置图片的右边框和上边框为不显示
    ax.spines['right'].set_color('none')
    ax.spines['top'].set_color('none')
    #挪动x，y轴的位置，也就是图片下边框和左边框的位置
    ax.spines['bottom'].set_position(('data',0))  #data表示通过值来设置x轴的位置，将x轴绑定在y=0的位置
    ax.spines['left'].set_position(('data',0))  #axes表示以百分比的形式设置轴的位置，即将y轴绑定在x轴50%的位置，也就是x轴的中点

    #绘制散点
    # 从左上角往右下角扫描
    x = Rec_left
    y = Rec_up
    pcount = 0
    #统计各种颜色的点数目
    w_count = 0 #白色 [-无穷,0]
    y_count = 0 #黄色 [0,10]
    b_count = 0 #棕色 [10,100]
    o_count = 0 #橙色 [100,1000]
    r_count = 0 #红色 [1000,+无穷]
    #统计人口总数
    sum_population = 0.0
    while y >= Rec_down:
        x = Rec_left
        while x <= Rec_right:
            #当前坐标
            p = [x,y]
            #如果坐标在多边形内,进行绘制
            if(_query.is_in_poly(p,polygonal_data["coordinates"])):
                sum_population += retList[pcount]
                #根据当前人口数目判定实心点颜色
                if pcount < len(retList):
                    population = retList[pcount]
                else:
                    population = -9999.0
                    print(f'out of range:pcount = {pcount} x={x} Rec_right = {Rec_right} y = {y} Rec_down = {Rec_down}')
                # print(f'type:{type(population)} population:{population}')
                #实心点颜色获取
                pcolor = getColor(population)
                if pcolor != 'white':
                    #添加筛选条件,避免程序崩溃
                    if pcount % 1000 == 0:
                        plt.plot(x,y,'o',color=pcolor)
                    
                #统计各种颜色点的数目
                if pcolor == 'white':
                    w_count = w_count+1
                elif pcolor == 'yellow':
                    y_count = y_count+1
                elif pcolor == 'brown':
                    b_count = b_count+1
                elif pcolor == 'orange':
                    o_count = o_count+1
                elif pcolor == 'red':
                    r_count = r_count+1
                else:
                    print(f'error color:{pcolor}')
                # plt.show()
            if pcount % 10000 == 0:
                print(f'pass {pcount} point')
            #右移一格
            pcount = pcount+1
            x += 0.0083333333333333
        #下移一格
        y -= 0.0083333333333333
    print(f'白色:{w_count}')
    print(f'黄色:{y_count}')
    print(f'棕色:{b_count}')
    print(f'橙色:{o_count}')
    print(f'红色:{r_count}')
    print(f'sum:{w_count + y_count + b_count + o_count + r_count}')
    print(f'总人口:{sum_population}')
    #设置图例
    p1 = plt.scatter(1, 1, c='red')
    p2 = plt.scatter(1, 1, c='orange')
    p3 = plt.scatter(1, 1, c='brown')
    p4 = plt.scatter(1, 1, c='yellow')
    p5 = plt.scatter(1, 1, c='white')
    plt.legend([p5,p4,p3,p2,p1],['-,0','0-0.1','0.1-0.2','0.2-0.5','0.5,+'], title='color')
    plt.show()